//
//  LoginViewController.m
//  HotWord
//
//  Created by Rainbow on 7/23/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "LoginViewController.h"
#import "ServiceHelper.h"
#import "PersonalInfoViewController.h"
#import "UserManager.h"
#import "MessageManager.h"
#import "UserInfoViewController.h"
#import "Match.h"

@interface LoginViewController ()

@end

@implementation LoginViewController
@synthesize switchModeBtn;
@synthesize containerScrollView;
@synthesize LoginView;
@synthesize loginUsernameTextField;
@synthesize loginPasswordTextField;
@synthesize registerView;
@synthesize registerEmailTextField;
@synthesize registerNicknameTextField;
@synthesize registerPasswordTextField;
@synthesize registerPasswordConfirmTextField;
@synthesize backBtn;
@synthesize loginBackgroundTableView;
@synthesize registerBackgroundTableView;
@synthesize pickContainerView;
@synthesize identitySelectPicker;
@synthesize identityBtn;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.registerView.bottom = 0;
    self.backBtn.alpha = 0;
    self.switchModeBtn.alpha = 0;

    _isLogin = YES;
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    
    UITapGestureRecognizer *tapGestureRecognizer = [[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTapGesture:)] autorelease];
    tapGestureRecognizer.delegate = self;
    [self.view addGestureRecognizer:tapGestureRecognizer];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [UIView animateWithDuration:0.3 
                     animations:^{
                         self.backBtn.alpha = 1;
                         self.switchModeBtn.alpha = 1;
                     }];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.pickContainerView.top = self.view.height;
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [[HTActivityIndicator currentIndicator] hide];
    [UIView animateWithDuration:0.3 
                     animations:^{
                         self.backBtn.alpha = 0;
                         self.switchModeBtn.alpha = 0;
                     }];
}


- (void)viewDidUnload
{
    [self setSwitchModeBtn:nil];
    [self setContainerScrollView:nil];
    [self setLoginView:nil];
    [self setLoginUsernameTextField:nil];
    [self setLoginPasswordTextField:nil];
    [self setRegisterView:nil];
    [self setRegisterEmailTextField:nil];
    [self setRegisterNicknameTextField:nil];
    [self setRegisterPasswordConfirmTextField:nil];
    [self setRegisterPasswordTextField:nil];
    [self setBackBtn:nil];
    [self setLoginBackgroundTableView:nil];
    [self setRegisterBackgroundTableView:nil];
    [self setPickContainerView:nil];
    [self setIdentitySelectPicker:nil];
    [self setIdentityBtn:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (IBAction)tapOnBackBtn:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)tapOnSwitchBtn:(id)sender {
    [self.containerScrollView setContentOffset:CGPointZero animated:YES];
    [_activeTextField resignFirstResponder];
    _isLogin = !_isLogin;
    if (_isLogin) {
        [UIView animateWithDuration:0.5 
                         animations:^{
                             self.registerView.bottom = 0;
                         } 
                         completion:^(BOOL finished){
                             [UIView animateWithDuration:0.5 
                                              animations:^{
                                                  self.LoginView.top = 54;
                                              }];
                         }];
    }
    else {
        
        [UIView animateWithDuration:0.5 
                         animations:^{
                             self.LoginView.bottom = 0;
                         } 
                         completion:^(BOOL finished){
                             [UIView animateWithDuration:0.5 
                                              animations:^{
                                                  self.registerView.top = 54;
                                              }];
                         }];
    }
}

- (IBAction)tapOnLoginBtn:(id)sender {
    [_activeTextField resignFirstResponder];
    if ([@"" isEqualToString:self.loginUsernameTextField.text]) {
        [[HTActivityIndicator currentIndicator] displayMessage:@"Please Enter Your Email"];
        return;
    }
    if ([@"" isEqualToString:self.loginPasswordTextField.text]) {
        [[HTActivityIndicator currentIndicator] displayMessage:@"Please Enter Your Password"];
        return;
    }
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setObject:self.loginUsernameTextField.text forKey:@"email"];
    [params setObject:self.loginPasswordTextField.text forKey:@"password"];
    [[ServiceHelper sharedService] requestServerForMethod:HotWordRequestTypeLogin WithParameters:params AndCallBackScope:self AndSuccessSel:@"loginSuccess:" AndFailedSel:@"loginFailed:"];
    [[HTActivityIndicator currentIndicator] displayActivity:@"Login..."];
    
}

- (void)loginSuccess:(NSObject *)result
{
    if (![result isKindOfClass:[NSDictionary class]]) {
        [[HTActivityIndicator currentIndicator] displayMessage:@"Login Failed!"];
        return;
    }
    NSDictionary *dic = (NSDictionary *)result;
    NSString *code = [dic objectForKey:@"code"];
    if ([@"0" isEqualToString:code]) {
        User *user = [[[User alloc] init] autorelease];
        NSString *userId = [UtilHelper getStringValue:[dic objectForKey:@"msg"]];
        user.userId = userId;
        user.email = self.loginUsernameTextField.text;
        user.password = self.loginPasswordTextField.text;
        NSDictionary *dataDic = [dic objectForKey:@"data"];
        user.nickname = [UtilHelper getStringValue:[dataDic objectForKey:@"nick"]];
        user.gender = [UtilHelper getStringValue:[dataDic objectForKey:@"gender"]];
        if ([@"F" isEqualToString:user.gender]) {
            user.gender = @"Girl";
        }
        else if ([@"M" isEqualToString:user.gender]) {
            user.gender = @"Boy";
        }
        user.longitude = [UtilHelper getStringValue:[dataDic objectForKey:@"longitude"]];
        user.latitude = [UtilHelper getStringValue:[dataDic objectForKey:@"latitude"]];
        user.avater = [UtilHelper getStringValue:[dataDic objectForKey:@"avater"]];
        user.avater1 = [UtilHelper getStringValue:[dataDic objectForKey:@"avater1"]];
        user.avater2 = [UtilHelper getStringValue:[dataDic objectForKey:@"avater2"]];
        user.exam = [UtilHelper getStringValue:[dataDic objectForKey:@"exam"]];
        NSInteger examType = [user.exam integerValue];
        if (IS_STRING_NOT_EMPTY(user.exam) && examType <= 6 && examType >= 0)
        {
            user.exam = [EXAM_ARRAY objectAtIndex:examType];
        }
        else
        {
            user.exam = @"";
        }
        
        BOOL isTeacher = [[UtilHelper getStringValue:[dataDic objectForKey:@"isTeacher"]] boolValue];
        if (isTeacher)
        {
            user.identity = @"Teacher";
        }
        else
        {
            user.identity = @"Student";
        }
        
        user.applyYear = [UtilHelper getStringValue:[dataDic objectForKey:@"applyYear"]];
        user.testSection = [UtilHelper getStringValue:[dataDic objectForKey:@"section"]];
        user.major = [UtilHelper getStringValue:[dataDic objectForKey:@"major"]];
        
        Match *match = [[Match alloc] init];
        match.matchType = [UtilHelper getStringValue:[dataDic objectForKey:@"filterType"]];
        match.dreamschool = [UtilHelper getStringValue:[dataDic objectForKey:@"dreamschoolName"]];
        match.examYear = [UtilHelper getStringValue:[dataDic objectForKey:@"examYear"]];
        match.examMonth = [UtilHelper getStringValue:[dataDic objectForKey:@"examMonth"]];
        match.examAddress = [UtilHelper getStringValue:[dataDic objectForKey:@"examAddress"]];
        user.match = match;
        [match release];
        
        user.lastLogin = [UtilHelper getStringValue:[dataDic objectForKey:@"lastLogin"]];
        user.lastMsg = [UtilHelper getStringValue:[dataDic objectForKey:@"lastMsg"]];
        user.year = [UtilHelper getStringValue:[dataDic objectForKey:@"year"]];
        user.country = [UtilHelper getStringValue:[dataDic objectForKey:@"country"]];
        user.city = [UtilHelper getStringValue:[dataDic objectForKey:@"city"]];
        user.status = [UtilHelper getStringValue:[dataDic objectForKey:@"status"]];
        user.dreamSchool = [UtilHelper getStringValue:[dataDic objectForKey:@"dreamSchool"]];
        user.dreamSchoolCN = [UtilHelper getStringValue:[dataDic objectForKey:@"dreamSchoolCn"]];
        user.dreamSchoolEN = [UtilHelper getStringValue:[dataDic objectForKey:@"dreamSchoolEn"]];
        [[UserManager sharedManager] saveLoginUser:user];
        [[HTActivityIndicator currentIndicator] displayMessage:[NSString stringWithFormat:@"%@, Welcome!", user.nickname]];
        
        if ([UserManager sharedManager].currentLocation2D.latitude != 0 && [UserManager sharedManager].currentLocation2D.longitude != 0) {
            [UserManager sharedManager].currentUser.longitude = [NSString stringWithFormat:@"%f", [UserManager sharedManager].currentLocation2D.longitude];
            [UserManager sharedManager].currentUser.latitude = [NSString stringWithFormat:@"%f", [UserManager sharedManager].currentLocation2D.latitude];
            NSMutableDictionary *params = [NSMutableDictionary dictionary];
            [params setObject:[UserManager sharedManager].currentUser.latitude forKey:@"latitude"];
            [params setObject:[UserManager sharedManager].currentUser.longitude forKey:@"longitude"];
            [params setObject:[UserManager sharedManager].currentUser.userId forKey:@"id"];
            [[ServiceHelper sharedService] requestServerForMethod:HotWordRequestTypeUpdateGeo WithParameters:params AndCallBackScope:nil AndSuccessSel:nil AndFailedSel:nil];
        }
        
        [[MessageManager sharedManager] sendReceiveMessage];
//        PersonalInfoViewController *personalInfoViewController = [[[PersonalInfoViewController alloc] init] autorelease];
//        [self.navigationController pushViewController:personalInfoViewController animated:NO];
        UserInfoViewController *userInfoViewController = [[UserInfoViewController alloc] init];
        [self.navigationController pushViewController:userInfoViewController animated:NO];
        
        if ([USER_DEFAULT stringForKey:USERDEFAULT_DEVICE_TOKEN]) {
            
            NSMutableDictionary *pushParams = [NSMutableDictionary dictionary];
            [pushParams setObject:[USER_DEFAULT stringForKey:USERDEFAULT_DEVICE_TOKEN] forKey:@"token"];
            [pushParams setObject:[UserManager sharedManager].currentUser.userId forKey:@"id"];
            [[ServiceHelper sharedService] requestServerForMethod:HotWordRequestTypeUploadToken WithParameters:pushParams AndCallBackScope:nil AndSuccessSel:nil AndFailedSel:nil];
        }
    }
    else {
        
        NSString *error = [UtilHelper getStringValue:[dic objectForKey:@"msg"]];
        [[HTActivityIndicator currentIndicator] displayMessage:error];
    }
}

- (void)loginFailed:(NSObject *)result
{
    [[HTActivityIndicator currentIndicator] displayMessage:@"Login Failed!"];
    
}

- (IBAction)tapOnRegisterBtn:(id)sender {
    [_activeTextField resignFirstResponder];
    if ([@"" isEqualToString:self.registerEmailTextField.text]) {
        [[HTActivityIndicator currentIndicator] displayMessage:@"Please Enter Your Email"];
        return;
    }
    if ([@"" isEqualToString:self.registerNicknameTextField.text]) {
        [[HTActivityIndicator currentIndicator] displayMessage:@"Please Enter Your Nickname"];
        return;
    }
    if ([@"" isEqualToString:self.registerPasswordTextField.text]) {
        [[HTActivityIndicator currentIndicator] displayMessage:@"Please Enter Your Password"];
        return;
    }
    if ([@"" isEqualToString:self.registerPasswordConfirmTextField.text]) {
        [[HTActivityIndicator currentIndicator] displayMessage:@"Please Confirm Your Password"];
        return;
    }
    if (![self.registerPasswordTextField.text isEqualToString:self.registerPasswordConfirmTextField.text]) {
        [[HTActivityIndicator currentIndicator] displayMessage:@"Twice Password Must Same"];
        return;
    }
    
//    NSString *identify = [self.identityBtn titleForState:UIControlStateNormal];
//    
//    if ([@"我是" isEqualToString:identify])
//    {
//        [[HTActivityIndicator currentIndicator] displayMessage:@"Please Select Your Identity"];
//        return;
//    }

    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setObject:self.registerEmailTextField.text forKey:@"email"];
    [params setObject:self.registerPasswordTextField.text forKey:@"password"];
    [params setObject:self.registerNicknameTextField.text forKey:@"nick"];
    
//    NSString *isTeacher = @"0";
//    
//    if ([@"Teacher" isEqualToString:identify])
//    {
//        isTeacher = @"1";
//    }
//    [params setObject:isTeacher forKey:@"isteacher"];

    [[ServiceHelper sharedService] requestServerForMethod:HotWordRequestTypeRegister WithParameters:params AndCallBackScope:self AndSuccessSel:@"registerSuccess:" AndFailedSel:@"registerFailed:"];
    [[HTActivityIndicator currentIndicator] displayActivity:@"Signup..."];
    
}

- (void)registerSuccess:(NSObject *)result
{
    if (![result isKindOfClass:[NSDictionary class]]) {
        [[HTActivityIndicator currentIndicator] displayMessage:@"Signup Failed!"];
        return;
    }
    NSDictionary *dic = (NSDictionary *)result;
    NSString *code = [dic objectForKey:@"code"];
    if ([@"0" isEqualToString:code]) {
        User *user = [[[User alloc] init] autorelease];
        NSString *userId = [UtilHelper getStringValue:[dic objectForKey:@"msg"]];
        user.userId = userId;
        user.email = self.registerEmailTextField.text;
        user.password = self.registerPasswordTextField.text;
        user.nickname = self.registerNicknameTextField.text;
        NSString *identify = [self.identityBtn titleForState:UIControlStateNormal];
        user.identity = identify;
        
        [[UserManager sharedManager] saveLoginUser:user];
        
        if ([UserManager sharedManager].currentLocation2D.latitude != 0 && [UserManager sharedManager].currentLocation2D.longitude != 0) {
            [UserManager sharedManager].currentUser.longitude = [NSString stringWithFormat:@"%f", [UserManager sharedManager].currentLocation2D.longitude];
            [UserManager sharedManager].currentUser.latitude = [NSString stringWithFormat:@"%f", [UserManager sharedManager].currentLocation2D.latitude];
            [[MessageManager sharedManager] sendReceiveMessage];
            NSMutableDictionary *params = [NSMutableDictionary dictionary];
            [params setObject:[UserManager sharedManager].currentUser.latitude forKey:@"latitude"];
            [params setObject:[UserManager sharedManager].currentUser.longitude forKey:@"longitude"];
            [params setObject:[UserManager sharedManager].currentUser.userId forKey:@"id"];
            [[ServiceHelper sharedService] requestServerForMethod:HotWordRequestTypeUpdateGeo WithParameters:params AndCallBackScope:nil AndSuccessSel:nil AndFailedSel:nil];
        }
        
        [[HTActivityIndicator currentIndicator] displayMessage:[NSString stringWithFormat:@"%@, Welcome!", user.nickname]];
//        PersonalInfoViewController *personalInfoViewController = [[[PersonalInfoViewController alloc] init] autorelease];
//        [self.navigationController pushViewController:personalInfoViewController animated:NO];
        UserInfoViewController *userInfoViewController = [[UserInfoViewController alloc] init];
        [self.navigationController pushViewController:userInfoViewController animated:NO];
        if ([USER_DEFAULT stringForKey:USERDEFAULT_DEVICE_TOKEN]) {
            
            NSMutableDictionary *pushParams = [NSMutableDictionary dictionary];
            [pushParams setObject:[USER_DEFAULT stringForKey:USERDEFAULT_DEVICE_TOKEN] forKey:@"token"];
            [pushParams setObject:[UserManager sharedManager].currentUser.userId forKey:@"id"];
            [[ServiceHelper sharedService] requestServerForMethod:HotWordRequestTypeUploadToken WithParameters:pushParams AndCallBackScope:nil AndSuccessSel:nil AndFailedSel:nil];
        }
    }
    else {
        
        NSString *error = [UtilHelper getStringValue:[dic objectForKey:@"msg"]];
        [[HTActivityIndicator currentIndicator] displayMessage:error];
    }

}

- (void)registerFailed:(NSObject *)result
{    
    [[HTActivityIndicator currentIndicator] displayMessage:@"Signup Failed!"];
}

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
//    if (!_isLogin) {
//        
//        if (textField == self.registerEmailTextField || textField == self.registerNicknameTextField) {
//            
//            [self.containerScrollView setContentOffset:CGPointMake(0, 55) animated:YES];
//        }
//        else {
//            
//            [self.containerScrollView setContentOffset:CGPointMake(0, 100) animated:YES];
//        }
//    }
    
    if (_activeTextField) {
        [_activeTextField release];
        _activeTextField = nil;
    }
    _activeTextField = [textField retain];
}

-(BOOL)textFieldShouldReturn:(UITextField*)textField
{
    NSInteger nextTag = textField.tag + 1;
    UIResponder* nextResponder = [textField.superview viewWithTag:nextTag];
    if (nextResponder)
    {
        [nextResponder becomeFirstResponder];
    }
    else
    {
        [textField resignFirstResponder];
        if (_isLogin)
        {
            [self tapOnLoginBtn:nil];
        }
//        else
//        {
//            [self tapOnIdentityBtn:nil];
//        }
    }
    return NO; 
}

-(void)keyboardWillShow:(NSNotification *)aNotification
{
//    if (_isLogin) {
//        
//        [self.containerScrollView setContentOffset:CGPointMake(0, 80) animated:YES];
//    }
    if (_isPickerShowing)
    {
        [self tapOnCancelBtn:nil];
    }
}

- (void)keyboardWillHide:(NSNotification *)aNotification
{
    [self.containerScrollView setContentOffset:CGPointZero animated:YES];
}

- (void)handleTapGesture:(UIGestureRecognizer *)recognizer
{
    [_activeTextField resignFirstResponder];
}

-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
    //Touch gestures below top bar should not make the page turn.
    //EDITED Check for only Tap here instead.
    
    if ([touch.view isKindOfClass:[UIButton class]] || [touch.view isKindOfClass:[UITextField class]] || _isPickerShowing)
    {
        return NO;
    }
    return YES;
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
{
    return YES;
}

#pragma mark - UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView == self.loginBackgroundTableView)
    {
        return 2;
    }
    return 5;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 1;
}

#pragma mark - UIPickerView

- (IBAction)tapOnIdentityBtn:(id)sender
{
    [UIView animateWithDuration:0.3
                     animations:^{
                         self.pickContainerView.top = self.view.height - self.pickContainerView.height;
                     }];
    _isPickerShowing = YES;
}

- (IBAction)tapOnCancelBtn:(id)sender
{
    [UIView animateWithDuration:0.3
                     animations:^{
                         self.pickContainerView.top = self.view.height;
                     }];
    _isPickerShowing = NO;
}

- (IBAction)tapOnConfirmBtn:(id)sender
{
    NSString *identity = [IDENTITY_ARRAY objectAtIndex:[self.identitySelectPicker selectedRowInComponent:0]];
    
    [self.identityBtn setTitle:identity forState:UIControlStateNormal];
    [self.identityBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [self.identityBtn setTitleColor:[UIColor blackColor] forState:UIControlStateHighlighted];
    
    [UIView animateWithDuration:0.3
                     animations:^{
                         self.pickContainerView.top = self.view.height;
                     }];
    _isPickerShowing = NO;
}


#pragma mark - UIPickerViewDelegate

// returns the # of rows in each component..
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    return [IDENTITY_ARRAY count];
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    if (row >= [IDENTITY_ARRAY count])
    {
        return nil;
    }
    return [IDENTITY_ARRAY objectAtIndex:row];
}




- (void)dealloc {
    [_activeTextField release];
    [switchModeBtn release];
    [containerScrollView release];
    [LoginView release];
    [loginUsernameTextField release];
    [loginPasswordTextField release];
    [registerView release];
    [registerEmailTextField release];
    [registerNicknameTextField release];
    [registerPasswordConfirmTextField release];
    [registerPasswordTextField release];
    [backBtn release];
    [loginBackgroundTableView release];
    [registerBackgroundTableView release];
    [pickContainerView release];
    [identitySelectPicker release];
    [identityBtn release];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
    [super dealloc];
}
@end
